//
//  LLStatus.swift
//  WeiBoShiBing
//
//  Created by Bingo on 15/10/31.
//  Copyright © 2015年 Bingo. All rights reserved.
//

import UIKit
import SDWebImage

class LLStatus: NSObject {
    
    var created_at:String?
    
    var id:Int = 0
    
    var text:String?{
        
        didSet{
            attrText = LLEmoticon.emticonStringToEmotionAttrString(text!,font: UIFont.systemFontOfSize(16))
            }
        }

    var source:String?{
    
        didSet{
            source = source?.linkSource() ?? "未知"
        
        }
    }
    
    var attrText:NSAttributedString?
    
    var user:LLUser?
    
    var retweeted_status:LLStatus?
    /// 微博的配图
    var pic_urls: [[String: AnyObject]]?{
        didSet {
            // 当字典转模型,给pic_urls赋值的时候,将数组里面的url转成NSURL赋值给storePictureURLs
            
            // 判断有没有图片
            let count = pic_urls?.count ?? 0
            // 没有图片,直接返回
            if count == 0 {
                return
            }
            // 创建storePictureURLs保存缩略图地址
            storePictureURLs = [NSURL]()
            
            //保存大图的url地址
            largeStorePictureURLs = [NSURL]()
            
            for dict in pic_urls! {
                if let urlString = dict["thumbnail_pic"] as? String {
                    // 有url地址
                    storePictureURLs?.append(NSURL(string: urlString)!)
                    
                    let largeUrlString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
//                    print("--------------------\(largeUrlString)")
                    
                    largeStorePictureURLs?.append(NSURL(string: largeUrlString)!)
                }
            }
        }
    }
    
    var largeStorePictureURLs: [NSURL]?
    var storePictureURLs: [NSURL]?
    
    var pictureURLs: [NSURL]? {
        get {
            
            return retweeted_status == nil ? storePictureURLs : retweeted_status!.storePictureURLs
        }
    }
    
    var largePictureURLs:[NSURL]?{
        get{
            return retweeted_status == nil ? largeStorePictureURLs : retweeted_status!.largeStorePictureURLs
        
        }
    }
    
    var rowHerght:CGFloat?
    
    func cellID()->String{
        
        return retweeted_status == nil ? LLStatusCellIdentifier.NormalCell.rawValue : LLStatusCellIdentifier.ForwardCell.rawValue
    }
    
    init(dict:[String:AnyObject]){
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        
        if key == "user"{
            if let dict = value as?[String:AnyObject]{
                
                user = LLUser(dict: dict)
                
                return
            }
        }else if key == "retweeted_status"{
            if let dict = value as?[String:AnyObject]{
                
                retweeted_status = LLStatus(dict: dict)
            }
            
            return
        }
        
        return super.setValue(value, forKey: key)
    }
    
    //MARK: - 当字典里的key在模型中没找到的时候，我们必须实现这个方法。不然会崩
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description:String{
        let p = ["created_at","idstr","text","source","pic_urls","user"]
        // 数组里面的每个元素,找到对应的value,拼接成字典
        // \n 换行, \t table
        return "\n\t微博模型：\(dictionaryWithValuesForKeys(p))"
    }
//    /// 加载微博数据
//    /// 没有模型对象就能加载数据
//    class func loadStatus(since_id: Int, max_id: Int, finished: (statuses: [LLStatus]?, error: NSError?) -> ()) {
//        
//        // 使用网络工具类加载微博数据
//        // 尾随闭包,当尾随闭包前面没有参数的时候()可以省略
//        LLNetworkTools.sharedInstance.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
//            if error != nil {
//                print("error:\(error)")
//                // 通知调用者
//                finished(statuses: nil, error: error)
//                return
//            }
//            
//            // 判断是否有数据
//            if let array = result?["statuses"] as? [[String: AnyObject]] {
//                // 有数据
//                // 创建模型数组
//                var statuses = [CZStatus]()
//                
//                for dict in array {
//                    // 字典转模型
//                    statuses.append(CZStatus(dict: dict))
//                }
//                
//                // 字典转模型完成
//                
//                // 缓存图片, 通知调用者
//                self.cacheWebImage(statuses, finished: finished)
//            } else {
//                // 没有数据,通知调用者
//                finished(statuses: nil, error: nil)
//            }
//        }
//    }
//    


    class func loadStatus(since_id: Int, max_id: Int, finished: (statuses: [LLStatus]?, error: NSError?) -> ()) {
        
        //TODO:测试数据保存
            LLStatusDAL.sharedInstance.loadStatus(since_id, max_id: max_id) { (array, error) -> () in
                
                if error != nil{
                    print("error:\(error)")
                    
                    finished(statuses: nil, error: error)
                    return
                }
                
                if  array != nil{
                    
                    //TODO:测试保存数据岛数据库
                    //                LLStatusDAL.sharedInstance.saveStatus(Array)
                    
                    var statuses = [LLStatus]()
                    //                print("22222\(result)")
                    for dict in array!{
                        
                        statuses.append(LLStatus(dict: dict))
                    }
                    
                    self.cacheWebImage(statuses, finished: finished)
                    
                    //                finished(statuses: statuses, error: nil)
                }else{
                    finished(statuses: nil, error: nil)
                }
    
        
        }
    }
    
    class func cacheWebImage(statuses:[LLStatus]?,finished:(statuses:[LLStatus]?,error:NSError?)->()) {
        
        let group = dispatch_group_create()
        
        guard let list = statuses else {
            return
        }
       
        var length = 0
        
        for status in list {
            let count = status.pictureURLs?.count ?? 0
            if count == 0{
                
                continue
    
            }
            
            if let urls = status.pictureURLs{
                
                if urls.count == 1{
                
                    let url = urls[0]
                    print(url)
                    
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue:0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                        
                        dispatch_group_leave(group)
                        
                        if error != nil{
                            print("下载图片出错：\(url)")
                            return
                        }
                        
                        print("下载图片完成：\(url)")
                        
                        if let data = UIImagePNGRepresentation(image){
                        
                            length += data.length
                        }
                    })
                    
                }
            }
            
        }
            // 所有图片都下载完,在通知调用者
            dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
                print("所有图片下载完成,告诉调用者获取到了微博数据: 大小:\(length / 1024)")
                // 通知调用者,已经有数据
                finished(statuses: statuses, error: nil)
            }
       }
}
